package com.iqilu.ksd.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.tedcoder.wkvideoplayer.constant.VideoType;
import com.android.tedcoder.wkvideoplayer.model.Video;
import com.android.tedcoder.wkvideoplayer.model.VideoUrl;
import com.android.tedcoder.wkvideoplayer.view.MediaController;
import com.android.tedcoder.wkvideoplayer.view.SuperVideoPlayer;
import com.facebook.drawee.view.SimpleDraweeView;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.MaterialDialog;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.iqilu.ksd.MyApplication;
import com.iqilu.ksd.R;
import com.iqilu.ksd.adapter.TVFragmentPagerAdapter;
import com.iqilu.ksd.bean.LiveBean;
import com.iqilu.ksd.bean.TabBean;
import com.iqilu.ksd.bean.UserBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.event.StopPlayRadioEvent;
import com.iqilu.ksd.event.StopPlayVideoEvent;
import com.iqilu.ksd.fragment.LiveCommentFragment;
import com.iqilu.ksd.fragment.LiveListFragment;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.NetworkUtils;
import com.iqilu.ksd.utils.ScreenUtils;
import com.iqilu.ksd.utils.ShareUtils;
import com.iqilu.ksd.widget.LigDialog;
import com.jude.swipbackhelper.SwipeBackHelper;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import okhttp3.Call;
import okhttp3.Request;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by Coofee on 2016/11/14.
 */

public class LiveActivity extends BaseActivity implements View.OnClickListener, EasyPermissions.PermissionCallbacks {

    private static final String TAG = "LiveActivity";

    private TVFragmentPagerAdapter adapter;
    private LiveListFragment listFragment;
    private LiveCommentFragment commentFragment;

    private LigDialog ligDialog;

    private ArrayList<Fragment> fragmentList;
    private ArrayList<String> titleList;
    private LiveBean data;
    private int mHeight; //封面高度
    private int screenWidth;
    private int screenHeight;
    private int id;
    private int userId;
    private int click;
    private String title;
    private String album;

    private RelativeLayout layTop;
    private SuperVideoPlayer superVideoPlayer;
    private SimpleDraweeView imgThumb;
    private TextView tvTitle;
    private TextView tvAuth;
    private ImageView btPlay;
    private ImageView btBack;
    private ImageView btMenu;
    private ImageView btLove;
    private CommonTabLayout tabMenu;
    private ViewPager vpContent;
    private RelativeLayout layLoading;
    private RelativeLayout layTitle;

    private UserBean user;
    private String[] mTitles;
    private int[] mIconUnselectIds = {R.drawable.ic_live_live_a, R.drawable.ic_live_comment_a};
    private int[] mIconSelectIds = {R.drawable.ic_live_live_b, R.drawable.ic_live_comment_b};
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();

    private SuperVideoPlayer.VideoPlayCallbackImpl mVideoPlayCallback = new SuperVideoPlayer.VideoPlayCallbackImpl() {
        @Override
        public void onCloseVideo() {
            superVideoPlayer.close();
            superVideoPlayer.setVisibility(View.VISIBLE);
            superVideoPlayer.setVisibility(View.GONE);
            resetPageToPortrait();
        }

        @Override
        public void onSwitchPageType() {
            if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                superVideoPlayer.setPageType(MediaController.PageType.SHRINK);
            } else {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                superVideoPlayer.setPageType(MediaController.PageType.EXPAND);
            }
        }

        @Override
        public void onPlayFinish() {

        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_live);
        ShareSDK.initSDK(this);
        user = ((MyApplication) getApplication()).getUser();
        id = getIntent().getIntExtra("id", 0);
        Log.i(TAG,"id====>"+id);
        initView();
        screenWidth = ScreenUtils.getScreenWidth(this);
        screenHeight = ScreenUtils.getScreenHeight(this);
        mHeight = screenWidth / 16 * 9;
        ViewGroup.LayoutParams params = layTop.getLayoutParams();
        params.width = screenWidth;
        params.height = mHeight;
        layTop.setLayoutParams(params);
        getContent();
    }

    private void initView() {
        layTop = getView(R.id.lay_top);
        superVideoPlayer = getView(R.id.superVideoPlayer);
        imgThumb = getView(R.id.img_thumb);
        tvTitle = getView(R.id.tv_title);
        setZHTypeface(tvTitle);
        tvAuth = getView(R.id.tv_auth);
        btPlay = getView(R.id.bt_play);
        btBack = getView(R.id.bt_back);
        btMenu = getView(R.id.bt_menu);
        btLove = getView(R.id.bt_love);
        tabMenu = getView(R.id.tab_menu);
        vpContent = getView(R.id.vp_content);
        layLoading = getView(R.id.lay_loading);
        layTitle = getView(R.id.lay_title);
        btPlay.setOnClickListener(this);
        btBack.setOnClickListener(this);
        btMenu.setOnClickListener(this);
        btLove.setOnClickListener(this);
    }

    private void iniTab() {
        mTitles = new String[]{getString(R.string.live_title), getString(R.string.live_comment)};
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabBean(mTitles[i], mIconSelectIds[i], mIconUnselectIds[i]));
        }
        tabMenu.setTabData(mTabEntities);
        tabMenu.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                vpContent.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
    }

    private void init() {
        userId = data.getUid();
        title = data.getTitle();
        click = data.getClick();
        album = data.getLitpic();
        if (data.getLivestatus() == 2 || data.getLivestatus() == 3) {
            btPlay.setVisibility(View.VISIBLE);
            imgThumb.setImageURI(Uri.parse("res://" + getPackageName() + "/" + R.drawable.cover_live_video));
        } else {
            imgThumb.setImageURI(Uri.parse(album));
        }
        tvTitle.setText(title);
        String auth = "";
        if (!TextUtils.isEmpty(data.getLiverolename())) {
            auth = String.format(getString(R.string.live_people), data.getLiverolename());
        } else {
            auth = String.format(getString(R.string.live_people), data.getNickname());
        }
        tvAuth.setText(auth);
        superVideoPlayer.setVideoPlayCallback(mVideoPlayCallback);
        if (data.getFavorited() == 1) {
            btLove.setImageResource(R.drawable.bt_live_love_blue);
        }
        Bundle bundle = new Bundle();
        bundle.putInt("id", id);
        bundle.putInt("userid", userId);
        bundle.putSerializable("videoList", data.getVideos());
        listFragment = new LiveListFragment();
        commentFragment = new LiveCommentFragment();
        listFragment.setArguments(bundle);
        commentFragment.setArguments(bundle);
        fragmentList = new ArrayList<>();
        fragmentList.add(listFragment);
        fragmentList.add(commentFragment);
        adapter = new TVFragmentPagerAdapter(getSupportFragmentManager(), fragmentList);
        vpContent.setAdapter(adapter);
        vpContent.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tabMenu.setCurrentTab(position);
                if (position == 0) {
                    SwipeBackHelper.getCurrentPage(LiveActivity.this).setSwipeBackEnable(true);
                } else {
                    SwipeBackHelper.getCurrentPage(LiveActivity.this).setSwipeBackEnable(false);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    public void setChoice(String url) {
        data.setLivestream(url);
        play();
    }

    private void play() {
        if (NetworkUtils.isWifiConnected(this)) {
            startPlay();
        } else if (NetworkUtils.isAvailable(this)) {
            showSelectDialog();
        } else {
            startPlay();
        }
    }

    private void showSelectDialog() {
        final MaterialDialog dialog = new MaterialDialog(this);
        dialog.content(getString(R.string.not_wifi))
                .btnText(getString(R.string.cancel), getString(R.string.continue_play))
                .show();
        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        startPlay();
                        dialog.dismiss();
                    }
                }
        );
    }

    private void startPlay() {
        Video video = new Video();
        VideoUrl videoUrl = new VideoUrl();
        videoUrl.setFormatName("480P");
        videoUrl.setFormatUrl(data.getLivestream());
        ArrayList<VideoUrl> arrayList1 = new ArrayList<>();
        arrayList1.add(videoUrl);
        video.setVideoName("");
        video.setVideoUrl(arrayList1);
        if (data.getLivestatus() == 2 || data.getLivestream().endsWith("m3u8")) {
            video.setmVideoType(VideoType.VIDEO_LIVE);
        } else {
            video.setmVideoType(VideoType.VIDEO_ONLINE);
        }
        ArrayList<Video> videoArrayList = new ArrayList<>();
        videoArrayList.add(video);
        superVideoPlayer.loadMultipleVideo2(videoArrayList, 0, 0, 0);

        btPlay.setVisibility(View.GONE);
        imgThumb.setVisibility(View.GONE);
        layTitle.setVisibility(View.GONE);
        superVideoPlayer.setVisibility(View.VISIBLE);
        EventBus.getDefault().post(new StopPlayVideoEvent());
        EventBus.getDefault().post(new StopPlayRadioEvent());
    }

    private void toShare() {
        Platform.ShareParams sp = new Platform.ShareParams();
        sp.setTitle(data.getTitle());
        sp.setTitleUrl(data.getShareurl());
        sp.setText(data.getDescription());
        sp.setSiteUrl(data.getShareurl());
        sp.setUrl(data.getShareurl());
        sp.setImageUrl(data.getShareicon());
        sp.setSite(getString(R.string.app_name));
        ShareUtils.getInstance().setShareParams(this, sp).show();
    }

    private void toFavorite() {
        if (user == null || user.getId() == 0) {
            Toast.makeText(this, R.string.not_login, Toast.LENGTH_SHORT).show();
            return;
        }
        if (data.getFavorited() == 1) {
            delFavorite();
        } else {
            addFavorite();
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_back:
                finish();
                break;
            case R.id.bt_play:
                play();
                break;
            case R.id.bt_menu:
                toShare();
                break;
            case R.id.bt_love:
                toFavorite();
                break;
            default:
                break;
        }

    }

    /***
     * 恢复屏幕至竖屏
     */
    private void resetPageToPortrait() {
        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            superVideoPlayer.setPageType(MediaController.PageType.SHRINK);
        }
    }

    /***
     * 旋转屏幕之后回调
     *
     * @param newConfig newConfig
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (null == superVideoPlayer) return;
        /***
         * 根据屏幕方向重新设置播放器的大小
         */
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().getDecorView().invalidate();
            layTop.getLayoutParams().height = (int) screenWidth;
            layTop.getLayoutParams().width = (int) screenHeight;
            superVideoPlayer.getLayoutParams().height = (int) screenWidth;
            superVideoPlayer.getLayoutParams().width = (int) screenHeight;
            Log.i(TAG, "screenWidth=" + screenWidth + ";screenHeight=" + screenHeight);
            toggleHide(true);
        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            final WindowManager.LayoutParams attrs = getWindow().getAttributes();
            attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(attrs);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            layTop.getLayoutParams().height = (int) mHeight;
            layTop.getLayoutParams().width = (int) screenWidth;
            superVideoPlayer.getLayoutParams().height = (int) mHeight;
            superVideoPlayer.getLayoutParams().width = (int) screenWidth;
            Log.i(TAG, "screenWidth=" + screenWidth + ";mHeight=" + mHeight);
            toggleHide(false);
        }
    }

    private void toggleHide(boolean hide) {
        int status;
        if (hide) {
            status = View.GONE;
        } else {
            status = View.VISIBLE;
        }
        btBack.setVisibility(status);
        btMenu.setVisibility(status);
        btLove.setVisibility(status);
    }

    private void getContent() {
        String url = Api.URL_LIVE_DETAIL + "?id=" + id;
        Log.i(TAG, "url=" + url);
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
                ligDialog = new LigDialog(LiveActivity.this, getString(R.string.waiting));
                ligDialog.show();
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                ligDialog.dismiss();
            }

            @Override
            public void onResponse(String response, int id) {
                ligDialog.dismiss();
                data = JSONUtils.requestDetail(response, "data", LiveBean.class);
                if (data == null) {
                    Toast.makeText(LiveActivity.this, R.string.live_load_error, Toast.LENGTH_SHORT).show();
                } else {
                    init();
                    iniTab();
                }
            }
        });
    }

    // 添加收藏
    private void addFavorite() {
        String url = Api.URL_FAVORITE;
        OkHttpUtils
                .post()
                .url(url)
                .addParams("articleid", "" + data.getId())
                .addParams("title", "" + data.getTitle())
                .addParams("catid", "0")
                .addParams("type", "live")
                .addParams("url", "")
                .addParams("thumb", "" + data.getLitpic())
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(LiveActivity.this, R.string.favorite_add_error, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        int status = 0;
                        status = JSONUtils.filterInt(response, "status", 0);
                        if (status == 1) {
                            Toast.makeText(LiveActivity.this, R.string.favorite_add_success, Toast.LENGTH_SHORT).show();
                            btLove.setImageResource(R.drawable.bt_live_love_blue);
                            data.setFavorited(1);
                        } else {
                            Toast.makeText(LiveActivity.this, R.string.favorite_add_error, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    // 删除收藏
    private void delFavorite() {
        int id = data.getId();
        String type = data.getType();
        String url = Api.URL_FAVORITE + "?articleid=" + id + "&type=live";
        Log.i(TAG, "url=" + url);
        OkHttpUtils.delete().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Toast.makeText(LiveActivity.this, R.string.favorite_del_error, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                Log.i(TAG, "response=" + response);
                int status = 0;
                status = JSONUtils.filterInt(response, "status", 0);
                if (status == 1) {
                    Toast.makeText(LiveActivity.this, R.string.favorite_del_success, Toast.LENGTH_SHORT).show();
                    btLove.setImageResource(R.drawable.bt_live_love);
                    data.setFavorited(0);
                } else {
                    Toast.makeText(LiveActivity.this, R.string.favorite_del_error, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            resetPageToPortrait();
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        superVideoPlayer.pausePlay(true);
    }
}
